package com.kstech.mp3604.fragments

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.kstech.mp3604.adapter.ErrorInfoAdapter
import com.kstech.mp3604.adapter.GridSpaceItemDecoration
import com.kstech.mp3604.bean.ErrorInfo
import com.kstech.mp3604.data.DbManager
import com.kstech.mp3604.databinding.FragmentQueryErrorBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 查询按钮-故障查询
 */
class QueryErrorFragment :
    BaseBindingFragment<FragmentQueryErrorBinding>(FragmentQueryErrorBinding::inflate) {
    private lateinit var errorAdapter: ErrorInfoAdapter
    private val dataList = ArrayList<ErrorInfo>()
    override fun onCreateInit() {

    }

    override fun onInitView() {
        lifecycleScope.launch(Dispatchers.IO) {
            val dataList = DbManager.db.errorInfoDao().queryAllErrorInfo()
            withContext(Dispatchers.Main) {
                if (dataList.size > 0) {
                    binding.emptyDataMsg.visibility = View.GONE
                    updateView(dataList)
                } else {
                    binding.emptyDataMsg.visibility = View.VISIBLE
                    binding.emptyDataMsg.text = "暂无数据"
                }
            }
        }
        binding.apply {
            /**
             * 如果查询的是空字符串，展示全部数据
             */
            queryButton.setOnClickListener {
                val searchValue = binding.searchByTime.text.toString().trim()
                lifecycleScope.launch(Dispatchers.IO) {
                    var dataList: MutableList<ErrorInfo>? = null
                    if (searchValue == "") {
                        dataList = DbManager.db.errorInfoDao().queryAllErrorInfo()

                    } else {
                        dataList = DbManager.db.errorInfoDao().queryFindErrorInfo(searchValue)
                    }

                    withContext(Dispatchers.Main) {
                        binding.emptyDataMsg.visibility = View.GONE
                        updateView(dataList)
                    }
                }
            }

            errorAdapter = ErrorInfoAdapter()
            recyclerView.layoutManager = LinearLayoutManager(requireActivity())
            recyclerView.addItemDecoration(GridSpaceItemDecoration(10, 10))
            recyclerView.adapter = errorAdapter
            errorAdapter.submitList(dataList)

        }
    }

    private fun updateView(dataList: MutableList<ErrorInfo>) {

        this.dataList.clear()
        this.dataList.addAll(dataList)
        errorAdapter.notifyDataSetChanged()
    }
}